<template>
  <el-card shadow="never" class="table-container">
    <div style="margin-bottom: 20px">
      <el-button type="primary" @click="handleBack">
        {{ $t("common.back") }}
      </el-button>
      <span
        v-if="task.formKey && task.formKey.startsWith('Task')"
        style="margin-left: 15px"
      >
        <el-button
          type="primary"
          @click="handleDealWith"
          v-if="task.delegationState != 'PENDING'"
        >
          {{ $t("flow.handle") }}
        </el-button>
        <el-button
          type="primary"
          v-hasPerm="['flow:task:goback']"
          @click="handleGoBack"
        >
          {{ $t("flow.goback") }}
        </el-button>
        <el-button type="primary" @click="handleTransfer">
          {{ $t("flow.transfer") }}
        </el-button>
        <el-button
          type="primary"
          @click="handleDelegate"
          v-if="task.delegationState != 'PENDING'"
        >
          {{ $t("flow.delegate") }}
        </el-button>
        <el-button
          type="primary"
          @click="handleResolve"
          v-if="task.delegationState == 'PENDING'"
        >
          {{ $t("flow.resolve") }}
        </el-button>
      </span>
      <span v-else style="margin-left: 15px">
        <el-button
          v-for="item in nodeButtonList"
          :key="item.buttonId"
          type="primary"
          @click="customButAction(item.buttonCode as string)"
        >
          {{ item.buttonName }}
        </el-button>
      </span>
    </div>
    <el-tabs type="border-card" v-model="activeName" @tab-click="tabClick">
      <el-tab-pane label="业务表单" name="businessForm">
        <component
          v-bind:is="current"
          ref="taskFromRef"
          v-model="taskDealWith"
          :task="task"
          @nodeButtonList="getNodeButtonList"
          @dealWith="handleDealWith"
          @transfer="handleTransfer"
          @delegate="handleDelegate"
          @resolve="handleResolve"
        ></component>
      </el-tab-pane>
      <el-tab-pane label="流程办理记录" name="record">
        <proc-inst-comment
          :proc-inst-id="task.processInstanceId"
        ></proc-inst-comment>
      </el-tab-pane>
      <el-tab-pane
        label="流程附件"
        name="attachment"
        v-if="task.formKey && (task.formKey as string).startsWith('Task')"
      >
        <task-attachment
          v-if="activeName === 'attachment'"
          :proc-inst-id="task.processInstanceId"
        />
      </el-tab-pane>
      <el-tab-pane label="流程图" name="diagram">
        <proc-inst-diagram
          :proc-inst-id="task.processInstanceId"
        ></proc-inst-diagram
      ></el-tab-pane>
    </el-tabs>
    <!--处理Dialog-->
    <task-deal-with-dialog
      v-if="taskDealWith.visible"
      v-model="taskDealWith"
      @refresh="handleBack"
    ></task-deal-with-dialog>
    <!--退回Dialog-->
    <task-goback-dialog
      v-if="gobackDialog.visible"
      v-model="gobackDialog.visible"
      :task-id="task.id"
      @refresh="handleBack"
    ></task-goback-dialog>
    <!--移交Dialog-->
    <task-transfer-dialog
      v-if="transferDialog.visible"
      v-model="transferDialog.visible"
      :title="transferDialog.title"
      :task-id="task.id"
      @refresh="handleBack"
    ></task-transfer-dialog>
    <!--委托Dialog-->
    <task-delegate-dialog
      v-if="delegateDialog.visible"
      v-model="delegateDialog.visible"
      :title="delegateDialog.title"
      :task-id="task.id"
      @refresh="handleBack"
    ></task-delegate-dialog>
    <!--完成委托Dialog-->
    <task-resolve-dialog
      v-if="taskDealWith.resolveVisable"
      v-model="taskDealWith"
      @refresh="handleBack"
    ></task-resolve-dialog>
  </el-card>
</template>
<script setup lang="ts">
import { ref, reactive, computed, defineAsyncComponent } from "vue";
import { useRoute, useRouter } from "vue-router";
import { type TabsPaneContext } from "element-plus";
import { routerUtil, type DialogRef } from "jmash-core";
import { useI18n } from "vue-i18n";
import { type NodeButtonModel } from "xyvcard-workflow";
import type { FlowTaskModel } from "@/api/flow/task/types";
import { taskApi } from "@/api/flow/task/index";
import type { TaskDealWith } from "@/api/flow/types";
import { registeredTaskComponents } from "@/taskcoms";
const { t } = useI18n();
const route = useRoute();
const router = useRouter();
const activeName = ref<string>("businessForm");
//切换Tab
const tabClick = (tab: TabsPaneContext, event: Event) => {
  activeName.value = tab.props.name as string;
};
const nodeButtonList = ref<NodeButtonModel[]>();
//动态组件
const currentA = ref(registeredTaskComponents["HolidayRequestTask"]);

//任务获取
const task = reactive({} as FlowTaskModel);
if (route.query.taskId) {
  taskApi.findTaskById(route.query.taskId as string).then((res) => {
    Object.assign(task, res.data);
    if (taskDealWith.value) {
      taskDealWith.value.taskId = task.id as string;
    }
    console.log(
      "FormKey:",
      task.formKey,
      registeredTaskComponents[task.formKey as string],
      task.formKey?.includes("Task"),
    );
    if (task.formKey && task.formKey.includes("Task")) {
      currentA.value = registeredTaskComponents[task.formKey];
    } else {
      console.log("FormKey:");
      currentA.value = registeredTaskComponents["FormDynamicCreate"];
    }
  });
}

//动态加载异步组件.
const current = computed(() => {
  return defineAsyncComponent(currentA.value as any);
});

//任务办理
const taskDealWith = ref<TaskDealWith>({ visible: false, vars: {} });
//任务表单.
const taskFromRef = ref<TaskCompent | null>(null);

export interface TaskCompent {
  changeModel(): Promise<boolean>;
  customButAction(buttonCode: string): void;
}

//办理.
function handleDealWith() {
  if (taskFromRef.value) {
    taskFromRef.value.changeModel().then((valid: boolean) => {
      taskDealWith.value.visible = true;
    });
  }
}

//退回Dialog
const gobackDialog = ref({
  title: t("flow.goback"),
  visible: false,
} as DialogRef);
// 退回
function handleGoBack() {
  gobackDialog.value.visible = true;
}

//委托完成
function handleResolve() {
  if (taskFromRef.value) {
    taskFromRef.value.changeModel().then((valid: boolean) => {
      taskDealWith.value.resolveVisable = true;
    });
  }
}

//移交Dialog
const transferDialog = ref({
  title: t("flow.transfer"),
  visible: false,
} as DialogRef);
// 移交
function handleTransfer() {
  transferDialog.value.visible = true;
}

//委托Dialog
const delegateDialog = ref({
  title: t("flow.delegate"),
  visible: false,
} as DialogRef);
// 委托
function handleDelegate() {
  delegateDialog.value.visible = true;
}

//返回、关闭当前页签.
function handleBack() {
  routerUtil.closeTagView(route.fullPath, router, false);
}

// 从子组件获取按钮列表
function getNodeButtonList(val: NodeButtonModel[]) {
  nodeButtonList.value = val;
}

function customButAction(buttonCode: string) {
  taskFromRef.value?.customButAction(buttonCode);
}
</script>
